package com.xuanyuanxinyu.utils.file

import android.content.Context
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import com.xuanyuanxinyu.utils.file.ContentFile
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext


/**
 * @FileName:ContentResolverHelper
 * @Description: ContentResolve帮助类
 * ContentResolve有3中方法:
 * 1. insert(...) 把新文件插入到指定Uri表中，后面跟数据库键值对。
 * 2. query(...) 搜索指定Uri下的媒体文件，后面是sql语句
 *
 *
 * val cursor = contentResolver.query(uri,projection,selection,selectionArgs,null)
 * uri：用于检索内容的 URI
 * projection：要返回的列的列表。传递 null 时，将返回所有列，这样会导致效率低下
 * selection：一种用于声明要返回哪些行的过滤器，其格式为 SQL WHERE 子句（WHERE 本身除外）。传递 null 时，将为指定的 URI 返回所有行
 * selectionArgs：您可以在 selection 中包含 ?s，它将按照在 selection 中显示的顺序替换为 selectionArgs 中的值。该值将绑定为字串符
 * sortOrder：行的排序依据，其格式为 SQL ORDER BY 子句（ORDER BY 自身除外）。传递 null 时，将使用默认排序顺序（可能并未排序）
 
 *
 * @author ken.luo
 * @date 2023/4/4
 * @version V1.0
 * @email 424533553@qq.com
 */
object ContentResolverHelper {
    /**
     * 查找手机中的图片文件
     */
    suspend fun getMediaImageInfo(ctx : Context,uri2 : Uri?) = withContext(Dispatchers.IO) {
        //可以手动指定获取的列
        val projection = arrayOf(
            MediaStore.Images.Media.DATA,MediaStore.Images.Media._ID,MediaStore.Images.Media.TITLE,MediaStore.Images.Media.DISPLAY_NAME,MediaStore.Images.Media.LATITUDE,MediaStore.Images.Media.LONGITUDE,MediaStore.Images.Media.DATE_TAKEN)
        val contentResolver = ctx.contentResolver
        val uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI //外部存储的SD卡的访问Uri,  content://media/external/images/media
        val uri3 = MediaStore.Images.Media.INTERNAL_CONTENT_URI  //Uri路径,content://media/internal/images/media
        // 获取全部列
        val cursor = contentResolver.query(uri,null,null,null,null)
        //        Cursor cursor = contentResolver.query(uri, columns, null, null, null);//获取指定列
        val result : MutableList<Map<*,*>> = ArrayList()
        if (cursor != null) {
            var item : MutableMap<String?,String?>? = null
            
            while (cursor.moveToNext()) {
                val columnNames = cursor.columnNames
                item = HashMap()
                for (colnmnName in columnNames) {
                    val columnIndex = cursor.getColumnIndex(colnmnName)
                    val columnValue = cursor.getString(columnIndex)
                    item[colnmnName] = columnValue
                }
                result.add(item)
            }
            cursor.close()
        }
        result
    }
    
    /**
     * 查找手机文件中的视频文件
     * ContentResolver contentResolver = ctx.getContentResolver();
     */
    suspend fun scanVideoFile(context : Context) = withContext(Dispatchers.IO) {
        Log.d("查询测试"," 开始 ")
        val contentResolver = context.contentResolver
        val folderPath = Environment.getExternalStorageDirectory().absolutePath + "/DCIM/OBSBOT" // 替换为您要扫描的文件夹路径
        val uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
        val projection = arrayOf(MediaStore.Video.Media.DATA)
        val selection = MediaStore.Video.Media.DATA + " like ?"
        val selectionArgs = arrayOf("$folderPath%")
        val cursor = contentResolver.query(uri,projection,selection,selectionArgs,null)
        if (cursor != null) {
            while (cursor.moveToNext()) {
                val filePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA))
                // 在这里可以使用您的逻辑来处理视频文件路径
                Log.d("查询测试"," filePath= $filePath")
            }
            cursor.close()
        }
    }
    
    /**
     * 方法说明:通过ContentResolver扫描手机指定文件夹中的文件
     * 一定要申请权限，否则无法查找到有效数据
     * <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
     *
     * @param folderPath = Environment.getExternalStorageDirectory().absolutePath + "/DCIM/OBSBOT"
     * @param description 过滤条件
     *    D  colnmnName =_data  ,columnValue= /storage/emulated/0/DCIM/OBSBOT/20230925_142011VIDN0221.MP4
     *    D  colnmnName =album  ,columnValue= OBSBOT
     *    D  colnmnName =bucket_display_name  ,columnValue= OBSBOT
     *    D  colnmnName =compilation  ,columnValue= null
     *    D  colnmnName =composer  ,columnValue= null
     *    D  colnmnName =_display_name  ,columnValue= 20230925_142011VIDN0221.MP4
     *    D  colnmnName =relative_path  ,columnValue= DCIM/OBSBOT/
     *    D  colnmnName =resolution  ,columnValue= 3840×2160
     *    D  colnmnName =_size  ,columnValue= 82627683
     *    D  colnmnName =volume_name  ,columnValue= external_primary
     *    D  colnmnName =title  ,columnValue= 20230925_142011VIDN0221
     */
    suspend fun scanContentFile(context : Context,folderPath : String,description : String) =
        withContext(Dispatchers.IO) {
        val contentResolver = context.contentResolver
        // 替换为您要扫描的文件夹路径
        val uri = MediaStore.Files.getContentUri("external")
        val projection = arrayOf(
            MediaStore.Files.FileColumns.DATA,
            MediaStore.Files.FileColumns.ALBUM,
            MediaStore.Files.FileColumns.BUCKET_DISPLAY_NAME,
            MediaStore.Files.FileColumns.COMPILATION,
            MediaStore.Files.FileColumns.COMPOSER,
            MediaStore.Files.FileColumns.DISPLAY_NAME,
            MediaStore.Files.FileColumns.RELATIVE_PATH,
            MediaStore.Files.FileColumns.RESOLUTION,
            MediaStore.Files.FileColumns.SIZE,
            MediaStore.Files.FileColumns.VOLUME_NAME,
            MediaStore.Files.FileColumns.AUTHOR,
            MediaStore.Files.FileColumns.TITLE)
//        val selection = MediaStore.Files.FileColumns.DATA + " like ? AND " + MediaStore.Images.Media.DESCRIPTION + " = ?"
//            val selectionArgs = arrayOf("$folderPath%",description)
             val selection = MediaStore.Files.FileColumns.DATA + " like ?"
        val selectionArgs = arrayOf("$folderPath%")
        
        val cursor = contentResolver.query(uri,projection,selection,selectionArgs,null)
        val list = arrayListOf<ContentFile>()
        if (cursor != null) {
            while (cursor.moveToNext()) {
                val columnNames = cursor.columnNames
                val filePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATA))
                val displayName = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DISPLAY_NAME))
                val title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.TITLE))
                val author = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.AUTHOR))
                list.add(ContentFile(filePath,displayName,title,author))
            }
            cursor.close()
        }
        list
    }
    
    
}